import 'dart:async';
import 'dart:io';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_is_know_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_package_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_single_upload_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import '../smart_home_upload_service.dart';


/// 发图片选择上传类型
class SmartHomeSelectImagePage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeSelectImagePage";
  final String shid;
  final List<ColumnListBean> columnList;
  final ColumnListBean currentColumn;
  final List<SmartHomeUploadItemBean> currentList;
  final String router;

  const SmartHomeSelectImagePage({Key key, this.shid, this.columnList, this.currentColumn, this.currentList, this.router})
      : super(key: key);

  @override
  SmartHomeSelectImagePageState createState() => SmartHomeSelectImagePageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String shid,
      List<ColumnListBean> columnList, ColumnListBean currentColumn,
      List<SmartHomeUploadItemBean> currentList, {String router}) {
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomeSelectImagePage(
        shid:shid,
        columnList:columnList,
        currentColumn:currentColumn,
        currentList:currentList,
        router:router,
      ),
      routeName: SmartHomeSelectImagePage.ROUTER,
    );
  }
}

class SmartHomeSelectImagePageState
    extends BaseState<SmartHomeSelectImagePage>
    with
        AutomaticKeepAliveClientMixin,
        NavigatorPageMixin {

  ///获取state
  static SmartHomeSelectImagePageState of(BuildContext context) {
    final SmartHomeSelectImagePageState result =
    context.findAncestorStateOfType<SmartHomeSelectImagePageState>();
    return result;
  }
  bool isAliveConfirm = false;

  List<SmartHomeUploadItemBean> _uploadList = List();
  //包含上传布局的默认数据
  List<SmartHomeUploadItemBean> _allList = List();

  ///自定义默认上传布局，type为-1
  SmartHomeUploadItemBean _defaultItem =
  new SmartHomeUploadItemBean(type: "-1");

  ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _uploadList.addAll(widget?.currentList);
    _allList.clear();
    _allList.addAll(_uploadList);
    _allList.add(_defaultItem);
    _scrollController = new ScrollController();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return LightAnnotatedRegion(
      child: Scaffold(
        backgroundColor: Color(0XFFF2F3F4),
        body: _toMainColumnWidget(),
      ),
    );
  }
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }
  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
          child: _toMainPlaceHolderWidget(),
        )
      ],
    );
  }

  Widget _toTopBarWidget() {
    final double statusHeight = ScreenUtils.getStatusBarH(context);
    return Container(
      height: 44 + statusHeight,
      color: Colors.white,
      padding: EdgeInsets.only(top: statusHeight),
      child: Row(
        children: <Widget>[
          ClickAnimateWidget(
            child: Container(
              width: 40,
              height: 44,
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(left: 15.6),
              child: Image.asset(
                "images/top_bar_back_ico.png",
                width: 9,
              ),
            ),
            scale: 1.4,
            onClick: () {
              FocusScope.of(context).requestFocus(FocusNode());
              Navigator.of(context).maybePop();
            },
          ),
          Text(
            "共${_uploadList.length}图",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                fontSize: 17,
                height: 1.22,
                fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  Widget _toMainPlaceHolderWidget() {
    return Column(
      children: <Widget>[
        Expanded(
          child: _toGridWidget(),
        ),
        _toBottomWidget(),
      ],
    );
  }

  Widget _toBottomWidget(){
    final double bottomH = ScreenUtils.getBottomBarH(context);
    return Container(
      padding: EdgeInsets.only(bottom: bottomH),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12)),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: Color(0xff000000).withOpacity(0.2),
                offset: Offset(0, -1),
                blurRadius: 10
            )
          ]
      ),
      child: Column(
        children: [
          _toSingleUpload(),
          Container(
            height: 1,
            color: Color(0XFFEEEEEE),
          ),
          _toPackageUpload(),
        ],
      ),
    );
  }

  ///独立上传
  Widget _toSingleUpload(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SmartHomePublishImageSingleUploadPage.navigatorPush(context, widget?.shid, _uploadList, router: widget?.router);
      },
      child: Container(
        height: 60,
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "独立上传",
                    style: TextStyle(
                        fontSize: 15,
                        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                        fontWeight: FontWeight.w600
                    ),
                  ),
                  Text(
                    "上传后生成多个独立文件",
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0XFF8B93A5),
                    ),
                  ),
                ],
              ),
            ),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  ///打包上传
  Widget _toPackageUpload(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_uploadList.length < 2){
          SmartHomeISeeDialog.navigatorPushDialog(context, content: "组图动态不得少于2张图片");
          return;
        }

        SmartHomePublishImagePackageUploadPage.navigatorPush(context, widget?.shid, currentList: _uploadList, router: widget?.router);
      },
      child: Container(
        height: 60,
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "打包上传",
                    style: TextStyle(
                        fontSize: 15,
                        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                        fontWeight: FontWeight.w600
                    ),
                  ),
                  Text(
                    "上传后生成一组文件",
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0XFF8B93A5),
                    ),
                  ),
                ],
              ),
            ),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }


  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toGridWidget(){
    return ScrollConfiguration(
        behavior: MyBehavior(),
        child: GridView.builder(
          padding: EdgeInsets.only(
              left: 15,
              right: 15,
              top: 10,
              bottom: getNavHeightDistance(context)),
          itemCount: _allList?.length ?? 0,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 4,
            crossAxisSpacing: 5,
            childAspectRatio: 1 / 1,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toGridItemWidget(context, index, _allList?.elementAt(index));
          },
        ));
  }

  Widget _toGridItemWidget(BuildContext context, int index, SmartHomeUploadItemBean itemBean) {
    double width = ScreenUtils.screenW(context) - 30 -10;
    if (itemBean?.isDefault() ?? false) {
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: throttle(() async {
          _selectImage();
          await Future.delayed(Duration(milliseconds: 2000));
        }),
        child: Container(
          width: width,
          height: width,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4), color: Colors.white),
          alignment: Alignment.center,
          child: Image.asset(
            "images/icon_smart_home_add_img.png",
            width: 40,
          ),
        ),
      );
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            VgCacheNetWorkImage(
              itemBean?.getPicOrVideoUrl() ?? "",
              width:width,
              height: width,
              imageQualityType: ImageQualityType.middleDown,
            ),
            Align(
              alignment: Alignment.topRight,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: (){
                  setState(() {
                    _uploadList?.removeAt(index);
                    _allList.clear();
                    _allList.addAll(_uploadList);
                    _allList.add(_defaultItem);
                  });
                  if(_uploadList?.length == 0){
                    RouterUtils.pop(context);
                  }
                },
                child: Padding(
                  padding: EdgeInsets.all(8),
                  child: Image.asset(
                    "images/icon_delete_img.png",
                    width: 15,
                    height: 15,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _selectImage() async {
    //图片
    List<String> resultList = await MatisseUtil.selectPhoto(
      context: context,
      maxSize: (35 - (_uploadList?.length??0)),
      maxAutoFinish: false,
      imageRadioMaxLimit: 3,
      imageRadioMinLimit: 0.3,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    _doHandleData(resultList);
  }

  void _doHandleData(List<String> resultList) {
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<SmartHomeUploadItemBean> selectList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    //获取选择的图片或者视频
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }
    loading(true, msg: "图片处理中");
    int computeCount = 0;
    resultList.forEach((element) {
      FileImage image = FileImage(File(element));
      image.resolve(new ImageConfiguration()).addListener(
          new ImageStreamListener((ImageInfo info, bool _) async {
            _imageInfoMap[element] = info;
            computeCount++;
            if (computeCount == resultList.length) {
              loading(false);
              resultList.forEach((element) {
                selectList.add(SmartHomeUploadItemBean(
                  localUrl: element,
                  type: "01",
                  folderWidth: _imageInfoMap[element].image.width,
                  folderHeight: _imageInfoMap[element].image.height,
                ));
              });
              setState(() {
                _uploadList.addAll(selectList);
                if (_uploadList.length < 35) {
                  _allList.clear();
                  _allList.addAll(_uploadList);
                  _allList.add(_defaultItem);
                } else {
                  _allList.clear();
                  _allList.addAll(_uploadList);
                }
              });
              Future.delayed(Duration(milliseconds: 300), () {
                _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
              });
            }
          }));
    });

  }

  @override
  bool get wantKeepAlive => true;
}
